package com.d3works.apps.stock.web;

import com.d3works.apps.ReportFactory;
import com.d3works.apps.base.db.Wizard;
import com.d3works.apps.report.engine.ReportSettings;
import com.d3works.apps.stock.db.StockLocation;
import com.d3works.apps.stock.db.repo.StockLocationRepository;
import com.d3works.apps.stock.exception.StockExceptionMessage;
import com.d3works.apps.stock.report.IReport;
import com.d3works.apps.stock.service.StockLocationService;
import com.d3works.exception.D3worksException;
import com.d3works.exception.service.TraceBackService;
import com.d3works.i18n.I18n;
import com.d3works.inject.Beans;
import com.d3works.meta.schema.actions.ActionView;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import com.d3works.rpc.Context;
import com.google.common.base.Joiner;
import com.google.inject.Singleton;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import org.eclipse.birt.core.exception.BirtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
public class StockLocationController {

  private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
  /**
   * Method that generate inventory as a pdf
   *
   * @param request
   * @param response
   * @return
   * @throws BirtException
   * @throws IOException
   */
  public void print(ActionRequest request, ActionResponse response) throws D3worksException {
    try {
      Context context = request.getContext();
      @SuppressWarnings("unchecked")
      LinkedHashMap<String, Object> stockLocationMap =
          (LinkedHashMap<String, Object>) context.get("_stockLocation");
      Integer stockLocationId = (Integer) stockLocationMap.get("id");
      StockLocationService stockLocationService = Beans.get(StockLocationService.class);
      StockLocationRepository stockLocationRepository = Beans.get(StockLocationRepository.class);

      StockLocation stockLocation =
          stockLocationId != null ? stockLocationRepository.find(new Long(stockLocationId)) : null;
      String locationIds = "";

      String printType = (String) context.get("printingType");
      String exportType = (String) context.get("exportTypeSelect");

      @SuppressWarnings("unchecked")
      List<Integer> lstSelectedLocations = (List<Integer>) context.get("_ids");
      if (lstSelectedLocations != null) {
        for (Integer it : lstSelectedLocations) {
          Set<Long> idSet =
              stockLocationService.getContentStockLocationIds(
                  stockLocationRepository.find(new Long(it)));
          if (!idSet.isEmpty()) {
            locationIds += Joiner.on(",").join(idSet) + ",";
          }
        }
      }

      if (!locationIds.equals("")) {
        locationIds = locationIds.substring(0, locationIds.length() - 1);
        stockLocation = stockLocationRepository.find(new Long(lstSelectedLocations.get(0)));
      } else if (stockLocation != null && stockLocation.getId() != null) {
        Set<Long> idSet =
            stockLocationService.getContentStockLocationIds(
                stockLocationRepository.find(stockLocation.getId()));
        if (!idSet.isEmpty()) {
          locationIds = Joiner.on(",").join(idSet);
        }
      }

      if (!locationIds.equals("")) {
        String language = ReportSettings.getPrintingLocale(null);

        String title = I18n.get("Stock location");
        if (stockLocation.getName() != null) {
          title =
              lstSelectedLocations == null
                  ? I18n.get("Stock location") + " " + stockLocation.getName()
                  : I18n.get("Stock location(s)");
        }

        if (stockLocationService.isConfigMissing(stockLocation, Integer.parseInt(printType))) {
          response.setNotify(I18n.get(StockExceptionMessage.STOCK_CONFIGURATION_MISSING));
        }

        String fileLink =
            ReportFactory.createReport(IReport.STOCK_LOCATION, title + "-${date}")
                .addParam("StockLocationId", locationIds)
                .addParam("Timezone", null)
                .addParam("Locale", language)
                .addFormat(exportType)
                .addParam("PrintType", printType)
                .generate()
                .getFileLink();

        logger.debug("Printing " + title);

        response.setView(ActionView.define(title).add("html", fileLink).map());

      } else {
        response.setInfo(I18n.get(StockExceptionMessage.LOCATION_2));
      }
      response.setCanClose(true);
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }

  public void setStocklocationValue(ActionRequest request, ActionResponse response) {

    StockLocation stockLocation = request.getContext().asType(StockLocation.class);
    if (stockLocation.getIsValued()) {
      response.setValue(
          "stockLocationValue",
          Beans.get(StockLocationService.class).getStockLocationValue(stockLocation));
    }
  }

  public void openPrintWizard(ActionRequest request, ActionResponse response) {
    StockLocation stockLocation = request.getContext().asType(StockLocation.class);

    @SuppressWarnings("unchecked")
    List<Integer> lstSelectedLocations = (List<Integer>) request.getContext().get("_ids");

    response.setView(
        ActionView.define(I18n.get(StockExceptionMessage.STOCK_LOCATION_PRINT_WIZARD_TITLE))
            .model(Wizard.class.getName())
            .add("form", "stock-location-print-wizard-form")
            .param("popup", "true")
            .param("show-toolbar", "false")
            .param("show-confirm", "false")
            .param("popup-save", "false")
            .context("_ids", lstSelectedLocations)
            .context("_stockLocation", stockLocation)
            .map());
  }
}
